<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Netty WebSocket Test</title>
    <style>
        body { font-family: Arial, sans-serif; }
        #messages { margin-top: 10px; }
    </style>
</head>
<body>
<h1>Netty WebSocket Test</h1>
<input type="text" id="messageInput" placeholder="Type a message">
<button onclick="sendMessage()">Send</button>
<br />
<input type="file" id="fileInput">
<button onclick="sendFile()">Send File</button>
<div id="messages"></div>

<script>
    // 创建 WebSocket 连接
    const socket = new WebSocket("ws://localhost:7000/ws");

    // 连接打开时触发
    socket.onopen = function () {
        console.log("Connected to WebSocket server.");
    };

    // 接收消息时触发
    socket.onmessage = function (event) {

        console.log("event :", event)

        const messagesDiv = document.getElementById("messages");

        if (event.data instanceof Blob) {
            // 如果是图片消息，创建 img 元素并设置 src 属性
            const reader = new FileReader()
            reader.onload = function (e) {

                console.log("e :", e)

                if (typeof e.target.result === 'string') {
                    const imgElement = document.createElement("img");
                    imgElement.src = e.target.result
                    imgElement.width = 200
                    messagesDiv.appendChild(imgElement)
                } else {
                    console.error("Unexpected result type:", typeof e.target.result);
                }
            }
            reader.readAsDataURL(event.data)
        }else {
            const messageElement = document.createElement("div");
            // 否则，创建 div 元素并设置文本内容
            messageElement.textContent = event.data;
            messagesDiv.appendChild(messageElement);
        }
    };

    // 发送消息
    function sendMessage() {
        const message = document.getElementById("messageInput").value;
        socket.send(message);
        document.getElementById("messageInput").value = ""; // 清空输入框
    }

    function sendFile() {
        const fileInput = document.getElementById("fileInput");

        console.log(fileInput)

        const file = fileInput.files[0];
        const reader = new FileReader();

        reader.onload = function (e) {
            const arrayBuffer = e.target.result;
            socket.send(arrayBuffer);
        };

        reader.readAsArrayBuffer(file);
    }

    // 连接关闭时触发
    socket.onclose = function (event) {
        console.log("WebSocket connection closed.", event);
    };

    // 发生错误时触发
    socket.onerror = function (error) {
        console.error("WebSocket error:", error);
    };
</script>
</body>
</html>